#coding:utf-8
"""关于获取房屋信息的视图"""

from ihome.api_1_0 import api
from flask import request, jsonify, current_app, session, g
from ihome.utils.response_code import RET
import re
from ihome.models import Area, House, Facility,HouseImage, Order
from werkzeug.security import check_password_hash
from ihome.utils.login_wrapper import login_wrapper
from ihome import redis_store, db
from ihome import constants
import json
from ihome.utils.avatar_upload import avatar_upload
from ihome.constants import UPLOAD_URL
from datetime import datetime




@api.route('/house/info',methods=['POST'])
@login_wrapper
def add_house():
    """
        json数据
        接收house新增加的信息,
        增加到数据库
    """

    # g变量中获取user_id
    user_id = g.user_id

    req_dict = request.get_json()

    area_id = req_dict.get('area_id')
    title = req_dict.get('title')
    price = req_dict.get('price')
    address = req_dict.get('address')
    room_count = req_dict.get('room_count')
    acreage = req_dict.get('acreage') # 房屋面积
    unit = req_dict.get('unit')
    capacity = req_dict.get('capacity')
    beds = req_dict.get('beds')
    deposit = req_dict.get('deposit')
    min_days = req_dict.get('min_days')
    max_days = req_dict.get('max_days')
    # order_count = req_dict.get('order_count')

    '''这两个暂且不获取
    index_image_url = req_dict.get('index_image_url')
    facilities = req_dict.get('facilities')
    '''
    if not all([area_id,title,price,address,room_count,acreage,unit,
                capacity,beds,deposit,min_days,max_days]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 对area_id进行判断
    try:
        area = Area.query.get(area_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询出错')
    if area is None:
        return jsonify(errno=RET.PARAMERR, errmsg='城区不存在')

    # 存数据

    house = House()
    house.user_id = user_id
    house.area_id = area_id
    house.title = title
    house.price = price
    house.address = address
    house.room_count = room_count
    house.acreage = acreage
    house.unit = unit
    house.capacity = capacity
    house.beds = beds
    house.deposit = deposit
    house.min_days = min_days
    house.max_days = max_days


    # 配套设施的获取
    # 前端怎么传配套设施过来??以列表的方式吧. facilities = ['1','2']
    # 当然这个数据也可以为无
    facilities = req_dict.get('facility')

    if facilities:
        # ["6','8']
        # 如果存在,进行判断是否id在Facility中,并获取所有对象
        try:
            facility_objs = Facility.query.filter(Facility.id.in_(facilities)).all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DATAERR, errmsg='数据错误')


        # 通过过后,将数据存入house中
        house.facilities = facility_objs #todo 这个可以直接存,系统会自动添加到中间表

    # 存数据
    db.session.add(house)

    # 存数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库存取失败')



    # 成功过后,返回数据house_id
    return jsonify(errno=RET.OK, errmsg='存入成功',data={'house_id':house.id})





@api.route('/house/picture',methods=['POST','GET'])
@login_wrapper
def add_house_picture():
    if request.method == 'POST':
        # 接收图片信息,然后保存到七牛
        # 图片与id

        pic = request.files.get('house_image')
        house_id = request.form.get('house_id')
        if not all([pic,house_id]):
            return  jsonify(errno=RET.PARAMERR, errmsg='参数不全')

        if not pic:
            return  jsonify(errno=RET.PARAMERR, errmsg='未选择图片')

        try:
            house = House.query.get(house_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')
        if not house:
            return jsonify(errno=RET.NODATA, errmsg='数据不存在')


        # 上传到七牛
        try:
            file_name = avatar_upload(pic.read())
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg='上传图片失败')

        # 上传成功,则返回file_name,设置url,添加到表
        house_image = HouseImage
        house_image.house_id = house_id
        house_image.url = file_name

        try:
            db.session.add(house_image)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='数据库错误')

        house_image_url = UPLOAD_URL + file_name

        return jsonify(errno=RET.OK, errmsg='存入成功',data={'house_image_url':house_image_url})

    '''
    # 这个查询图片的功能可以暂时不写,因为通过改变html源码就可以解决
    if request.method == 'GET':
        house_id = request.get_json('house_id')
        if not all([house_id]):
            return jsonify(errno=RET.PARAMERR, errmsg='参数不全')

        try:
            house = House.query.get(house_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='数据库错误')
        if not house:
            return jsonify(errno=RET.NODATA, errmsg='数据不存在')

        # 取图片
        try:
            house_image_li = HouseImage.query.filter_by(house_id=house_id).all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='数据库错误')

        # url需要拼接前面的http



        return jsonify(errno=RET.OK, errmsg='查询数据成功',data={'house_image'})

    '''





# GET /api/v1.0/houses?sd=2017-12-01&ed=2017-12-31&aid=10&sk=new&p=1
@api.route('/houses',methods=['GET'])
def get_house_list():
    """
    实现搜索页的返回
    数据:入住日期与截止日期,区域,最新上线/入住最多/价格, 页数
        sd        ed     aid   sk=new/...         p
    """
    req_dict = request.args
    #todo 由于这些信息都可以为空,所以默认为''
    start_date = req_dict.get('sd','')  # 入住日期
    end_date = req_dict.get('ed','')  # 截止日期
    area_id = req_dict.get('aid','')  # 区域编号
    sort_key = req_dict.get('sk','')  # 搜索排序关键字
    page = req_dict.get('p')  # 页码

    # house_query对象
    house_query = House.query

    '''
    不先直接接收参数,而是先返回数据,看能否跑通
    '''
    # houses_obj_list =  House.query.all()
    # houses = [h.to_dict() for h in houses_obj_list]

    '''能跑通,接下来处理这些接收的数据,然后返回相应值'''
    '''start_date  怎么处理??
        house里面本身没这个属性,就只有借助于order表
        排除
        时间的过滤

         format: "yyyy-mm-dd", 前端传过来的格式
    '''

    '''排除时间'''
    # 如果时间不为空,就对其进行格式化,时间为空,就pass掉
    if start_date:
        try:
            start_date = datetime.strptime(start_date,"%Y-%m-%d")
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg='开始时间参数出错')

    if end_date:
        try:
            end_date = datetime.strptime(end_date, "%Y-%m-%d")
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg='结束时间参数出错')

    # 时间为空的,格式化后的时间都出现在这里了

    if start_date and end_date:
        exclusive_order = Order.query.filter(Order.begin_date <= end_date, Order.end_date >= start_date)
    elif start_date:
        exclusive_order = Order.query.filter(Order.end_date >= start_date)
    elif end_date:
        exclusive_order = Order.query.filter(Order.begin_date <= end_date)
    else:
        exclusive_order = None

    try:
        exclusive_order_li = exclusive_order.all()
    except Exception as e:
        current_app.logger.error(e)  #没有这个值会报错
    else:
        house_ids = [e.house_id for e in exclusive_order_li]
        # 排除house_id
        house_query = house_query.filter(House.id.notin_(house_ids))


    '''查询地区'''
    # 判断area_id有效性
    if area_id:
        try:
            area = Area.query.get(area_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg='地区id参数出错')

        if not area:
            return jsonify(errno=RET.PARAMERR, errmsg='地区id参数出错')
        else:
            house_query = house_query.filter_by(area_id=area_id)


    '''sort_key排序'''
    # 补充排序条件
    if sort_key == "booking":  # 入住做多
        house_query = house_query.order_by(House.order_count.desc())
    elif sort_key == "price-inc":  # 价格升
        house_query = house_query.order_by(House.price.asc())
    elif sort_key == "price-des":  # 价格降
        house_query = house_query.order_by(House.price.desc())
    else:  # 新旧
        house_query = house_query.order_by(House.create_time.desc())


    '''执行分页查询'''
    if page:
        try:
            page = int(page)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg='page参数出错')
    else:
        page = 1  # 默认为1


    try:
        #                               当前页数          每页数据量                              自动的错误输出
        page_obj = house_query.paginate(page=page, per_page=constants.HOUSE_LIST_PAGE_CAPACITY, error_out=False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库异常")

    # 获取页面数据
    house_li = page_obj.items
    houses = []
    for house in house_li:
        houses.append(house.to_dict())

    # 获取总页数
    total_page = page_obj.pages

    resp_dict = dict(errno=RET.OK, errmsg="OK", data={"total_page": total_page, "houses": houses, "current_page": page})
    resp_json = json.dumps(resp_dict)

    return resp_json, 200, {'Content-Type':'application/json'}




    # # exclusive_method =
    # #                        开始时间<=结束时间             结束时间>=查询时间
    # exclusive_order = Order.query.filter(Order.begin_date <= end_date,Order.end_date >= start_date).all()
    # # 找出所有house_id
    # house_ids = [e.house_id for e in exclusive_order]
    # # 排除house_id
    # houses_obj_list = House.query.filter(House.id.notin_(house_ids)).all()
    #
    #
    # '''区域的过滤'''
    # houses_obj_list = House.query.filter_by(area_id=area_id).all()
    #
    # '''搜索关键字的过滤'''
    # # houses_obj_list.order_by('-id')
    #
    #
    # '''过滤条件怎么融合起来呢?'''
    #
    # houses_obj_list = House.query.filter_by(area_id=1).filter_by(user_id=11).all()
    # houses = [h.to_dict() for h in houses_obj_list]
    #
    #
    #
    #
    #
    # return jsonify(houses=houses)




'''
# 添加order数据用
@api.route('/add_order')
def add_order():
    order = Order()
    order.user_id = 11
    order.house_id = 1
    order.begin_date = '2017-12-01'
    order.end_date = '2017-12-05'
    order.days = 4
    order.house_price = 100
    order.amount = 2
    db.session.add(order)
    db.session.commit()
    return 'ok'
'''















